# 目标文件名
TARGET = main

# 源文件路径
SRCDIR = user
LIBDIR = Libraries
INCDIR = $(LIBDIR)/CMSIS $(LIBDIR)/STM32F10x_StdPeriph_Driver/inc
STARTUPDIR = $(LIBDIR)/CMSIS/startup

# 输出路径
OBJDIR = obj
BINDIR = bin

# 编译器
CC = arm-none-eabi-gcc
AS = arm-none-eabi-as
LD = arm-none-eabi-ld
AR = arm-none-eabi-ar
SIZE = arm-none-eabi-size

# 编译器标志
CFLAGS = -mcpu=cortex-m3 -mthumb -O2 -Wall -I$(INCDIR) -I./Libraries/STM32F10x_StdPeriph_Driver/inc
ASFLAGS = -mcpu=cortex-m3 -mthumb
#LDFLAGS = -Tstm32_flash.ld -nostartfiles -Wl,-Map,$(BINDIR)/$(TARGET).map
LDFLAGS = -Tstm32_flash.ld -nostdlib

# 源文件
SRCS = $(wildcard $(SRCDIR)/*.c) \
       $(wildcard $(LIBDIR)/CMSIS/*.c) \
       $(wildcard $(LIBDIR)/STM32F10x_StdPeriph_Driver/src/*.c)

OBJS = $(patsubst $(SRCDIR)/%.c,$(OBJDIR)/%.o,$(SRCS:.c=.o))

# 默认目标
all: $(BINDIR)/$(TARGET).elf

# 编译C文件
$(OBJDIR)/%.o: $(SRCDIR)/%.c
	@mkdir -p $(OBJDIR)
	$(CC) $(CFLAGS) -c $< -o $@

$(OBJDIR)/%.o: $(LIBDIR)/CMSIS/%.c
	$(CC) $(CFLAGS) -c $< -o $@

$(OBJDIR)/%.o: $(LIBDIR)/STM32F10x_StdPeriph_Driver/src/%.c
	$(CC) $(CFLAGS) -c $< -o $@

# 编译汇编文件
$(OBJDIR)/%.o: $(STARTUPDIR)/%.s
	@mkdir -p $(OBJDIR)
	$(AS) $(ASFLAGS) -c $< -o $@

# 链接目标文件
$(BINDIR)/$(TARGET).elf: $(OBJS)
	@mkdir -p $(BINDIR)
	$(LD) $(LDFLAGS) -o $@ $(OBJS)
	$(SIZE) $@

# 清理
clean:
	rm -rf $(OBJDIR) $(BINDIR)

.PHONY: all clean
